﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Threading;

/*还有这些bug没有修改好
 * 1. listbox 选中的时候，再去勾选 mofidy 会出发 无引用的对象
 * 2. richText 能够直接通过 修改添加进来，不合适 （如果这里加进来的 没有 & 会导致后续分割 超出数组界限）

     */

namespace FoxStart
{
    public partial class Form1 : Form
    {
        string path;
        bool Timekey = false;
        int timemodify = 1; // min

        //bool ModfListB1 = false;

        bool canin = true;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Form1.CheckForIllegalCrossThreadCalls = false; // 这句话很重要，访问
            timer1.Enabled = false;
            Form2 f;
            f = new Form2();
            f.ShowDialog();
            int TT = 60 * 1000 * f.GetChangeValue();
            path = f.GetPath();
            if (path.Length > 0)
            {
                //StreamReader sr = new StreamReader(path, Encoding.Default);
                StreamReader sr = new StreamReader(path, Encoding.GetEncoding("UTF-8"));
                String line;
                int Ww = 0;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line == "======这是未完成事项======")
                    {
                        Ww = 1;
                        continue;
                    }
                    else if (line == "======这是已完成事项======")
                    {
                        Ww = 0;
                        continue;
                    }
                    else
                    {
                        if (Ww == 1)
                        {
                            checkedListBox1.Items.Add(line);
                        }
                        else
                        {
                            listBox1.Items.Add(line);
                        }
                    }
                    //Console.WriteLine(line.ToString());
                }
            }

            //开始自动保存线程
            Thread o1Thread = new Thread(() => with5min());
            //Woshiyigejishiqi(time, pob, nowstring);
            o1Thread.Start();

            timer1.Interval = TT;
            label5.Text = (TT / 60 / 1000).ToString() + " Min";
            timer2.Interval = 1000;
            timer1.Enabled = true;

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            Type oleType = Type.GetTypeFromProgID("Shell.Application");
            object oleObject = System.Activator.CreateInstance(oleType);
            oleType.InvokeMember("ToggleDesktop", BindingFlags.InvokeMethod, null, oleObject, null);//报错地方自行引用空间名
            //MessageBox.Show("Time Get ...");
            Form3 f;
            f = new Form3();
            f.ShowDialog();
            timer1.Enabled = true;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            string[] sArray = DateTime.Now.ToString().Split(':');
            label1.Text = sArray[0] + ":" + sArray[1];
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void chart1_Click(object sender, EventArgs e)
        {

        }

        private void fontDialog1_Apply(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string Text = this.richTextBox1.Text.Trim().ToString();
            ListBox list = this.checkedListBox1;
            string[] sArray = DateTime.Now.ToString().Split(':');
            list.Items.Add(Text + " " + sArray[0] +":"+ sArray[1]);
            richTextBox1.Clear();
        }

        private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (string item in checkedListBox1.CheckedItems)
            {
                //string[] sArray = DateTime.Now.ToString().Split(':');
                //listBox1.Items.Add("0&"+item.ToString() + " " + sArray[0] + ":" + sArray[1]);
                listBox1.Items.Add("0&" + item.ToString());
                checkedListBox1.Items.Remove(item);
                break;
            }
        }

        private void checkedListBox1_ItemCheck(object sender, EventArgs e)
        {
            
        }

        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void timer3_Tick(object sender, EventArgs e)
        {

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            gettotxt();
            //with5min();
        }

        private void button2_MouseEnter(object sender, EventArgs e)

        {

            bool _isBtnCutoutToolTip = false; //在MouseEnter事件里做一个判断就好了， 

            if (_isBtnCutoutToolTip) return; //_isBtnCutoutToolTip在第一次tooltip.SetToolTip()设置之后赋值为true即可。这样就不会重复设置提示框了导致多提示框了

            ToolTip p = new ToolTip();

            p.ShowAlways = true;

            p.SetToolTip(this.button2, "直接关闭就可以");

            _isBtnCutoutToolTip = true;

        }

        public void with5min()
        {
            int min = 5;
            while (true)
            {
                //string puG="G:\\ak" + DateTime.Now.ToString("D") + ".txt";
                string puG = DateTime.Now.ToString("yyyy-MM-dd")+"_temp.txt"; 
                FileStream fs = new FileStream(puG, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("======这是未完成事项======");
                foreach (string item in checkedListBox1.Items)
                {
                    sw.WriteLine(item.ToString());
                    //也可以使用fs 用byte的方式写入，但是不好换行
                }
                sw.WriteLine("======这是已完成事项======");
                foreach (string item in listBox1.Items)
                {
                    sw.WriteLine(item.ToString());
                    //也可以使用fs 用byte的方式写入，但是不好换行
                }
                sw.Flush();
                sw.Close();
                //System.Diagnostics.Process.Start(puG);
                Thread.Sleep(1000 * 60 * min);
            }

        }

        public void gettotxt()
        {
            //string puG="G:\\ak" + DateTime.Now.ToString("D") + ".txt";
            string puG = DateTime.Now.ToLocalTime().ToString().Replace(":", "_").Replace(" ", "#").Replace("/", "_") + ".txt"; ;
            FileStream fs = new FileStream(puG, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine("======这是未完成事项======");
            foreach (string item in checkedListBox1.Items)
            {
                sw.WriteLine(item.ToString());
                //也可以使用fs 用byte的方式写入，但是不好换行
            }
            sw.WriteLine("======这是已完成事项======");
            foreach (string item in listBox1.Items)
            {
                sw.WriteLine(item.ToString());
                //也可以使用fs 用byte的方式写入，但是不好换行
            }
            sw.Flush();
            sw.Close();
            System.Diagnostics.Process.Start(puG);
            Application.Exit();
        }


        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        bool can1in = true;

        private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            if (checkBox1.Checked && can1in)//&& ! Timekey
            {
                //添加一个变量，防止第二次进来 -- 在 修改 按钮 里设置为 true
                can1in = false;

                //checkBox1.Checked = false; //让 修改 按钮，自己取消，不在这里取消，不然 Woshiyigejishiqi 线程会自己放出来。

                //string tmp1 = listBox1.SelectedItem.ToString();

                //sstoflag → 添加时间换算功能
                richTextBox1.Text = sstoflag(listBox1.SelectedItem.ToString());

                //Thread.Sleep(1000 * 1 * timemodify);
                if (listBox1.SelectedItem.ToString().Replace(" ","").Length>0) //避免没选中的时候，删了不应该删除的
                {
                    listBox1.Items.Remove(listBox1.SelectedItem);
                }
                //listBox1.Items.Remove(richTextBox1.Text);

                //ModfListB1 = true;

            }
        }

        public void Woshiyigejishiqi(int nowtips,string nowstring,string stringP)
        {   // stringP 的话，是 tips + string

            if (!canin) //避免其他线程进入

                /*
             跟多线程进入没关系，是前一个还没有退出导致的问题   
             
            真是原因是：同时有五个线程进来是什么鬼，在没退出的时候(sleep的时候)，又进来了其他线程
            
             导致前面的线程不再会退出了。

            换成线程外的直接停止呢？

             */
            {
                return;
            }
            canin = false;
            int newtips = nowtips;
            while (Timekey && ! checkBox1.Checked)
            {
                //修复问题 -> 处理重复添加的问题
                //stringP = (newtips.ToString() + "&" + nowstring); //不是因为这个问题，是因为多个函数进入的问题，添加控制，只让一个函数进入就可以

                // 光标移走后，没有选中的，第二次循环过来就会报错-> 放到第一次调用这个函数之前的位置
                //label7.Text = listBox1.SelectedItem.ToString();//标识现在开始记时的item

                Thread.Sleep(1000 * 1 * timemodify);
                //Thread.SpinWait(1000*60* timemodify); 不行不行，严重不符合预期
                newtips += 1;
                listBox1.Items.Remove(stringP);
                //int nIndex = listBox1.FindString(stringP);
                stringP =(newtips.ToString() + "&" + nowstring);
                listBox1.Items.Add(stringP);
                //---//20170908//  try
                //---//20170908//  {
                //---//20170908//      listBox1.Items[nIndex] = stringP;
                //---//20170908//  }
                //---//20170908//  catch
                //---//20170908//  {
                //---//20170908//      label2.Text = stringP;
                //---//20170908//      //listBox1.Items[nIndex] = stringP;
                //---//20170908//      //吃掉最后一次刷新Ithems的错误
                //---//20170908//  }
                
                if (Timekey) {
                    if (nowstring.Length > 39)
                    {
                        label7.Text = nowstring.Substring(0, 40);
                    }
                    else {
                        label7.Text = nowstring;
                    }
                }

                //这是ClistBox的用法 参考链接 修改listbox里某一行的文字_百度知道  https://zhidao.baidu.com/question/174404737.html
                //int nIndex = listbox.FindString搜索(-1, _T("待修改字符串"));
                //listbox.DeleteString(nIndex);
                //listbox.InsertString(nIndex, _T("修改后字符串"));
            }

            canin = true; 
            //这个处理时很ok的
            //从 if (Timekey) 里面移过来，期望解决重复添加，多个线程一起的情况

            //label5.Text = nowtips.ToString();
        }

        public void Woshiyigejishiqi2(int nowtips, string nowstring, string stringP)
        {   

            if (!canin) 
            {
                return;
            }
            canin = false;
            int newtips = nowtips;
            while (Timekey && !checkBox1.Checked)
            {
                Thread.Sleep(1000 * 1 * timemodify);
                newtips += 1;
                listBox2.Items.Remove(stringP);
                stringP = (newtips.ToString() + "&" + nowstring);
                listBox2.Items.Add(stringP);
                
                if (Timekey)
                {
                    if (nowstring.Length > 39)
                    {
                        label7.Text = nowstring.Substring(0, 40);
                    }
                    else
                    {
                        label7.Text = nowstring;
                    }
                }
            }

            canin = true;
        }

        private void listBox1_Click(object sender, EventArgs e)
        {
            if (listBox1.Items.Count<1|| listBox1.SelectedIndex == -1)
            {
                return;
            }
            string nowstring = listBox1.SelectedItem.ToString();//"我就是个计时的";
            int time = Int32.Parse(nowstring.Split('&')[0]);
            string pob = nowstring.Split('&')[1];
            // 这里肯定是没问题的，因为我们肯定是单线程处理问题的，不应该同时处理两个事项
            //不得已 可以切换，但是不会有并行
            if (! checkBox1.Checked)
            {
                if (Timekey)
                {
                    Timekey = false;
                    label7.Text = "No with doing";//标识现在开始记时的item

                }
                else
                {
                    Timekey = true;
                    if (listBox1.SelectedItem.ToString().Length > 39)
                    {
                        label7.Text = listBox1.SelectedItem.ToString().Substring(0, 40);//标识现在开始记时的item
                    }//上面这个语句不能放到 函数 Woshiyigejishiqi 里面去，因为可能出现 无 SelectedItem 的情况
                    else
                    {
                        label7.Text = listBox1.SelectedItem.ToString();
                    }
                    Thread oThread = new Thread(() => Woshiyigejishiqi(time, pob, nowstring));
                    //Woshiyigejishiqi(time, pob, nowstring);
                    oThread.Start();

                    // Loop until worker thread activates.
                    //while (!oThread.IsAlive) ;

                }
            };
        }

        private void listBox2_Click(object sender, EventArgs e)
        {
            if (listBox2.Items.Count < 1 || listBox2.SelectedIndex == -1)
            {
                return;
            }
            string nowstring = listBox2.SelectedItem.ToString();
            int time = Int32.Parse(nowstring.Split('&')[0]);
            string pob = nowstring.Split('&')[1];
            if (!checkBox1.Checked)
            {
                if (Timekey)
                {
                    Timekey = false;
                    label7.Text = "No with doing";

                }
                else
                {
                    Timekey = true;
                    if (listBox2.SelectedItem.ToString().Length > 39)
                    {
                        label7.Text = listBox2.SelectedItem.ToString().Substring(0, 40);
                    }
                    else
                    {
                        label7.Text = listBox2.SelectedItem.ToString();
                    }
                    Thread oThread = new Thread(() => Woshiyigejishiqi2(time, pob, nowstring));
                    oThread.Start();
                    

                }
            };
        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private string sstoflag(string ss)
        {
            int time = Int32.Parse(ss.Split('&')[0]);
            int time1 = time / 3600;
            int time2 = (time % 3600) / 60+1;
            string pob = ss.Split('&')[1];

            int ww_1 = pob.IndexOf("]");
            if (ww_1 > 0)
            {
                pob = pob.Substring(ww_1+1);
            }

            string sflag = "["+time1.ToString()+"h"+time2.ToString()+"min" + "]";
            string flag = time + "&" + sflag+ pob;

            return flag;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (richTextBox1.Text.Replace(" ","").Length>0) { 
            listBox1.Items.Add(richTextBox1.Text);
            }
            //ModfListB1 = false;
            can1in = true;
            checkBox1.Checked = false;
            richTextBox1.Text = "";
           Timekey = false;
            label7.Text = "No with doing";//标识现在开始记时的item
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string Text = this.richTextBox1.Text.Trim().ToString();
            ListBox list = this.checkedListBox2;
            string[] sArray = DateTime.Now.ToString().Split(':');
            list.Items.Add(Text + " " + sArray[0] + ":" + sArray[1]);
            richTextBox1.Clear();
        }

        private void checkedListBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (string item in checkedListBox2.CheckedItems)
            {
                //string[] sArray = DateTime.Now.ToString().Split(':');
                //listBox2.Items.Add("0&" + item.ToString() + " " + sArray[0] + ":" + sArray[1]);
                listBox2.Items.Add("0&" + item.ToString());
                checkedListBox2.Items.Remove(item);
                break;
            }
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked && can1in)//&& ! Timekey
            {
                //添加一个变量，防止第二次进来 -- 在 修改 按钮 里设置为 true
                can1in = false;

                //checkBox1.Checked = false; //让 修改 按钮，自己取消，不在这里取消，不然 Woshiyigejishiqi 线程会自己放出来。

                //string tmp1 = listBox1.SelectedItem.ToString();

                //sstoflag → 添加时间换算功能
                richTextBox1.Text = sstoflag(listBox2.SelectedItem.ToString());
                
                //Thread.Sleep(1000 * 1 * timemodify);
                if (listBox2.SelectedItem.ToString().Replace(" ", "").Length > 0) //避免没选中的时候，删了不应该删除的
                {
                    listBox2.Items.Remove(listBox2.SelectedItem);
                }
                //listBox1.Items.Remove(richTextBox1.Text);

                //ModfListB1 = true;

            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (richTextBox1.Text.Replace(" ", "").Length > 0)
            {
                listBox2.Items.Add(richTextBox1.Text);
            }
            //ModfListB1 = false;
            can1in = true;
            checkBox1.Checked = false;
            richTextBox1.Text = "";
            Timekey = false;
            label7.Text = "No with doing";//标识现在开始记时的item

        }

        private void label8_Click_1(object sender, EventArgs e)
        {

        }
    }
}
